﻿using RXY_Mall.AdminApi.Common;

using RXY_Mall.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using RXY_Mall.Services;

public class ModelValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        try
        {
            if (actionContext.ModelState.IsValid == false)
            {
                LogHelper.WriteLog("ActionFilterAttribute");
                ResponseService<string> result = new ResponseService<string>();
                result.code = 0;
                result.msg = "";
                // Return the validation errors in the response body.
                // 在响应体中返回验证错误
                foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
                {
                    LogHelper.WriteLog(string.Format("{0}:{1}", keyValue.Key, keyValue.Value));  
                    foreach (var error in keyValue.Value.Errors)
                    {
                        if (!string.IsNullOrEmpty(error.ErrorMessage))
                        {                            
                            result.msg += error.ErrorMessage + "\r\n";
                        }
                        if (error.Exception != null && !string.IsNullOrEmpty(error.Exception.Message))
                        {
                            result.msg += error.Exception.Message + "\r\n";
                        }
                    }
                    if (!string.IsNullOrEmpty(result.msg))
                    {
                        result.msg = result.msg.Remove(result.msg.Length - 2, 2);
                        break;
                    }
                }
                var errorMessage = JsonConvert.SerializeObject(result);
                LogHelper.WriteLog(errorMessage);
                
                actionContext.Response = HttpResponseExtension.toJson(errorMessage);
                
            }
        }
        catch (Exception ex)
        {
            LogHelper.WriteLog(ex);
        }
        
        base.OnActionExecuting(actionContext);
    }
}